Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/DbTerminal.jsm");

/*设备信息对象数组初始化*/
var deviceInfo = [{status:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
/*全局设备信息*/
//var deviceName =null;
var offdeviceName=null;
var deviceSYS="Android";
var gDeviceWindowObj = null;

/*全局监控数组，当数组内增添新设备，或移除设备时触发*/
var addflag = null;
var rmflag = null;
var devlivenum=null;
var myObservableArray = ko.observableArray();
//var i=0;
myObservableArray.subscribe(function (newVal) {

    var dateval = Date.now();
    //flag = true;
    if (rmflag === "removeOk")
    {
        //alert('removeOK');
        //alert("removeOK");
        document.getElementById('offline').setAttribute('label', dateval);
        rmflag = null;
    }
    if (addflag === "add")
    {
        //alert('add');
        //var newdevice=deviceName;
       // i++;
       // alert("push="+i+"次");
        document.getElementById('online').setAttribute('label', dateval);
        addflag = null;
    }
    //alert("全局数组长度="+newVal.length);

});
/*触发离线提醒*/
function getDeviceBey()
{
    //alert(12324423232);
    //var deviceName = "三星5056";
    //alert(567894);
    var deviceLoser = offdeviceName + "设备离线";
    //alert(deviceLoser);
    var alertsService = Components.classes["@mozilla.org/alerts-service;1"].
            getService(Components.interfaces.nsIAlertsService);
    try {
        var timestring = getAliveAndBeyTime();
        alertsService.showAlertNotification('', deviceLoser, timestring, false, '', null, '');
        deviceLoser=null;
    } catch (e)
    {
        debug("发生错误 => " + timestring + "\n");
    }
//    var box = document.getElementById("msg-footer-notification-box");
//    var onlineDevName=box.getAttribute("statustext");
//    if(onlineDevName===offdeviceName.uuid)
//    {
//        alert(67891);
//        //box=getNotificationWithValue(offdeviceName.uuid);
//        //alert(box);
//        //removeNotification(box);
//    }
//    alert(12345);  
}
/*触发上线提醒*/
function getDeviceAlive()
{
    
    //myObservableArray()[devlivenum].name
    
    var devlist = gEN.getdevice();
    var uuid = Components.ID("{5aaf3bbd-993e-4402-a1ea-73a1a07a6e4b}");
    var device = devlist.queryElementAt(devlivenum, uuid);
    var ondevname=convertToUnicode(device.name);
    var messageString = ondevname + "设备已在线，      " + "该设备的操作系统版本为： " + deviceSYS + "，上线" + getAliveAndBeyTime() + "。";
    var box = document.getElementById("deviceOnLine");//msg-footer-notification-box
    box.setAttribute("statustext",device.uuid);
    var buttons = [{
            label: '连接',
            accessKey: '连',
            popup: null,
            callback: function (aNotificationBar, aButton)
            {
                //alert(ondevname);
                 var flag;
                 var numberc;
                 var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dHandleStatus,count(dId) AS numbers FROM td_device where dUDN = :myVal");
                  statement.params.myVal = device.uuid;
                 try {
                 while (statement.executeStep()) {
                       flag = statement.row.dHandleStatus;
                       numberc= statement.row.numbers;
                      }
                   }
                 finally {
                  statement.reset();
                }
                if(numberc===0||flag)
                {
                     box.removeCurrentNotification();
                }
                else
                {
                    toShowlinkDevicePanel(device,dDeviceSqlite);
                }
                
            }
        }];

    var priority = box.PRIORITY_INFO_LOW;
    //alert(messageString);
    box.appendNotification(messageString, device.uuid, 'chrome://messenger/skin/icons/link.png', priority, buttons);
}//var listenerboard;

/*触发同步提醒*/
function showSyncInfo()
{
    dDeviceSqlite.onLoad();
    var tempSync=gEN.sync;
//   var tempSync=1;
    if(tempSync!==null)
    {
        //alert(tempSync);
        var allAccount = tempSync.split(":");
        for(var i = 0;i < allAccount.length - 1;i++)
        {
            var oneAccount = allAccount[i].split("_");
//            for(var j = 0; j < oneAccount.length;j++)
//            {
//                alert(oneAccount[j]);
//            }
            var accountXml = oneAccount[1] + "_message.xml";
            var statement = dDeviceSqlite.dbConnection.createStatement("\
            SELECT dId FROM td_device WHERE dName = :myVal"); 
            statement.params.myVal =oneAccount[0];
            var deviceId = null;
            try{
                    while(statement.executeStep()){
                    deviceId = statement.row.dId;
                    continue;
                }
            }
            finally{
                    statement.reset();
            }
            statement = dDeviceSqlite.dbConnection.createStatement("\
                     SELECT aId ,aName,aXml FROM td_account WHERE dId = :myVal");
            statement.params.myVal =deviceId;
            var tempXml = null;
            var accoutName = null;
            try{
                    while(statement.executeStep())
                    {
                        tempXml = statement.row.aXml;
                        if(tempXml === accountXml)
                        {                       
                            accoutName = statement.row.aName;
                        }
                        continue;
                    }
            }
            finally{
                    statement.reset();
            }
            var recv = null;
            var send = null;
            var draft = null;
            if(oneAccount[2][0] === "1")
            {
                recv = "发件箱";
            }
            else
            {
                recv = null;
            }
            
            if(oneAccount[2][1] === "1")
            {
                send = "收件箱";
            }
            else
            {
                send = null;
            }
            if(oneAccount[2][2] === "1")
            {
                send = "草稿箱";
            }
            else
            {
                draft = null;
            }
            if(send !== null || recv !==null || draft !==null)
            {
                var message = oneAccount[0] + " 设备的 " + accoutName + " 账户的 ";
                if(send !== null)
                    message += send;
                if(recv !== null)
                    message += recv;
                if(draft !== null)
                    message += draft;
                message += "有同步请求";
                var box = document.getElementById("syncinfonotify");//msg-footer-notification-box
                var notifyId= Date.now();
                var priority = box.PRIORITY_INFO_LOW;
                box.appendNotification(message, notifyId, 'chrome://messenger/skin/icons/syncnotify.png', priority, "");
            }
           
        }
       gEN.sync=null; 
    }
    else
    {
    }
    
}
//setTimeout(getDeviceAliveOrBey,500);
//window.addEventListener("load",getDeviceAliveOrBey,false);
//window.setInterval(getDeviceAliveOrBey,60000);


/*获取上线及下线时间*/
function getAliveAndBeyTime()
{
    var date1 = new Date();
    var nowdateString = "时间：  " + date1.getHours().toString() + "时" + date1.getMinutes().toString() + "分" + date1.getSeconds().toString() + "秒";
    return nowdateString;
}

//window.addEventListener("load",testComponents,false);
/*启动TB时自动开启UPNP服务*/
window.addEventListener("load", function () {
    setTimeout(function () {
        upnpInit();
        dDeviceSqlite.onLoad();
    }, 0);
});
/*TB关闭时关闭UPNP服务*///compose-window-close beforeunload focus mousemove
window.addEventListener("close", closeUpnpService, false);

/*upnp服务开启*/
/*
function testComponents()
{
    //alert("begin");
    //document.getElementById('valueChanger').setAttribute('label','jinhaidawagn');
    //if(flag) return;
    var cmgr = Components.classes["@nfs.hlj/testsample1;1"].getService();
    if (cmgr)
    {
        //alert("success");
        cmgr = cmgr.QueryInterface(Components.interfaces.nsISample1);
        //alert(cmgr.value);
        //cmgr.poke(name);
        var ipval = cmgr.getIpAndPort();
        alert(ipval);
        //cmgr.writeValue(name);
        //alert(cmgr.value);
    }
    else
    {
        alert("error");
    }

    //addDev();
    //removeDev();
    //testDevice();
    //switchp=setTimeout(testComponents,500);
}
*/
/*upnp服务初始化*/
var gEN = Components.classes["@nfs.hlj/upnpservice;1"].getService();//createInstance(Components.interfaces.nsIUpnpService);
gEN = gEN.QueryInterface(Components.interfaces.nsIUpnpService);

var lisenerDevlist=function () {
    setTimeout(function () {getDeviceArray();}, 0);};

var lisenerSyncInfo=function () {
    setTimeout(function () {showSyncInfo();}, 0);};

/*开启UPNP服务*/
function upnpInit()
{
    //alert("start");
    //deleteDeviceInfoInDB();
    gEN.upnpinit();
    //getDeviceArray();
    window.addEventListener("focus",lisenerDevlist,false);
    window.addEventListener("mousemove",lisenerDevlist,false);
    
    window.addEventListener("focus",lisenerSyncInfo,false);
    window.addEventListener("mousemove",lisenerSyncInfo,false);
}
/*关闭UPNP服务*/
function closeUpnpService()
{
    
    //gEN.finishupnp();
    window.removeEventListener("focus",lisenerDevlist,false);
    window.removeEventListener("mousemove",lisenerDevlist,false);
    //alert(1);
    window.removeEventListener("focus",lisenerSyncInfo,false);
    window.removeEventListener("mousemove",lisenerSyncInfo,false);
   // alert(2);
    
    deleteDeviceInfoInDB();   //删除数据库中的设备表及账户表,信息头表，及通讯录表
    //alert(3);    
    //rmflag="removeOk";
    gEN.finishupnp();
    myObservableArray.removeAll();
    var panelTree = document.getElementById("folderPaneBox");
    var elem_child = panelTree.childNodes; 
     //alert(menuItem.getAttribute("checked"));
     if(panelTree){
         for(var i=0;i<elem_child.length;i++){
            if("showDevicesPanelTree"=== elem_child[i].id){
                  elem_child[i].parentNode.removeChild(elem_child[i]);         
            }
         }
     }
   var  treeSpr = document.getElementById("hadTreeOrNewTree");
    if(treeSpr){
        treeSpr.parentNode.removeChild(treeSpr);
     }
}


/*测试发送指定的动作*/
function sentActionTest()
{
    var locationStr;
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation FROM td_device where dHandleStatus = :myVal");
                  statement.params.myVal = 1;
                 
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    alert(serviceSubStr);
    gEN.SendAction(serviceSubStr,"PowerOn","deviceInfo.xml"); 
    alert("动作完成");
}
/*字符转码UTF-8,主要用于读文件*/
//function convertToUnicode(aStr) {  
// }  
///*字符转码，主要用于写文件*/
//function convertFromUnicode(aStr) {  
// }  
/*比较当前入网设备数组与全局监控数组
 * 
 * 判断入网设备数组内元素变化，新增设备调用函数addDev()
 * 移除设备调用函数 removeDev()
 * */
function getDeviceArray()
{
    //alert(1111111111);
    //gEN.checkstateflag="";
    var devlist = gEN.getdevice();
    var uuid = Components.ID("{5aaf3bbd-993e-4402-a1ea-73a1a07a6e4b}");
    //alert(gEN.checkstateflag);
    if(devlist.length!==0)//&&gEN.checkstateflag!=="none"
    {    
      //alert("devlist.length="+devlist.length); 
       if(addDev(devlist,uuid))
       {   
         removeDev(devlist,uuid);
       }   
     }
     /*唯一在线设备的离线与beybey退出*/
 if(devlist.length===0 && myObservableArray().length===1)//
 {
         //gEN.checkstateflag="";  
        //alert("进入我"+gEN.checkstateflag)
        //alert("删除唯一在线设备="+gEN.checkstateflag);
        //gEN.checkstateflag="abcd";
        var lastdevice=myObservableArray()[0];
        offdeviceName=convertToUnicode(lastdevice.name);
        deleteOffDevDBInfo(lastdevice.uuid);
        rmflag = "removeOk";
        myObservableArray.remove(lastdevice);
        //myObservableArray.removeAll();
 }
   /*    
   else if(gEN.getdevice().length===0&&gEN.checkstateflag==="have")
       {
        alert("删除唯一在线设备="+gEN.checkstateflag);
        gEN.checkstateflag="abcd";
        var lastdevice=myObservableArray()[0];
        offdeviceName=convertToUnicode(lastdevice.name);
        deleteOffDevDBInfo(lastdevice.uuid);
        rmflag = "removeOk";
        myObservableArray.remove(lastdevice);
       } */ 
        //removeDev(devlist,uuid);    
    
}
//var complexListModel = function(items) {
//            var self = this;
//            self.items = [];
//            ko.utils.arrayForEach(items, function (item) {
//                var i = {
//                    num:ko.observable(item.num),
//                    addr:ko.observable(item.addr),
//                    name:ko.observable(item.name),
//                    prob:ko.observable(item.prob)
//                };
//                self.items.push(i);
//            });
//            self.items = ko.observableArray(self.items);
//        };
/*设备上线,添加设备到列表
 * 
 * 传入新上线的设备，更新全局数组
 *
 * */
function addDev(devlist,uuid)
{
   //alert(devlist.length);
     for (var i = 0; i < devlist.length; i++)
      {
        //alert(i);
        var device = devlist.queryElementAt(i, uuid);
        //alert("device"+i+"的名字="+device.name);
        var easitflag;
                
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT count(dId) AS numbers FROM td_device where dUDN = :myVal");
                  statement.params.myVal = device.uuid;
                 
        try {
                 while (statement.executeStep()) {
                       easitflag = statement.row.numbers;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
                //myObservableArray.indexOf(device) === -1
                //alert("easitflag="+easitflag);
        if (easitflag===0)
        {
            //alert(easitflag+"addflag");
            //alert("11111111");
            addflag = "add";
            //alert("addev->gEN.checkstateflag="+gEN.checkstateflag);
            var deviceName=convertToUnicode(device.name);
            //var deviceInfo = [{status:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
            addOneDeviceInfo(deviceInfo, 0, device.location,deviceName, device.uuid);
            getOneDeviceInfos(deviceInfo);
            deviceInfo.length = 0;//ary.length = 0;
            devlivenum=i;
            //alert("device"+i+"的名字="+deviceName); 
            myObservableArray.push(device);
        }

      }
      return 1;
}

/*设备下线，移除设备到列表
 * 
 *传入移除的设备，更新全局列表
 *更新数据库内信息
 * 
 * */
function removeDev(devlist,uuid)
{
    
    //var revOprFlag=true;
    var getlistid;
    var deletedevid;
    var deviceL=devlist.length;
    //alert("devlist.length的长度为："+devlist.length);
     for (var j = 0; j < myObservableArray().length; j++)
    {
        //alert("deviceL="+deviceL);
        for (var i = 0; i < deviceL; i++)    
      {
        var device = devlist.queryElementAt(i, uuid);  
        if (myObservableArray()[j].uuid!==device.uuid)
        {
       
            //alert("第一步-》"+"saveFlagState[i]值为："+saveFlagState[i]);
            getlistid = i+1;
            deletedevid=j;
            //alert("deletedevid="+deletedevid);
            //alert("getlistid="+getlistid);
            continue;  
        }else{
            //alert("jump");
            break;
        
            }
          
            
      }
      if(getlistid===deviceL)  
      {
            rmflag = "removeOk";
            //myObservableArray.remove(myObservableArray()[j]);
            //alert(device.uuid);
            //alert("删除-》"+myObservableArray()[deletedevid].name);
            deleteOffDevDBInfo(myObservableArray()[deletedevid].uuid);
            offdeviceName=convertToUnicode(myObservableArray()[deletedevid].name);
            myObservableArray.remove(myObservableArray()[deletedevid]);
          
      }    

 }
}
/*删除下线设备已存储的信息*/
function deleteOffDevDBInfo(id)
{
    
    var offdeviceid;
    var emailAccount=[];
    var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT dId  FROM td_device where dUDN = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                        offdeviceid= statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
        
         /*删除离线设备的头信息*/
         var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT aXml   FROM td_account where dId = :myVal");
                  statement.params.myVal = offdeviceid;
                 
        try {
                 while (statement.executeStep()) {
                        emailAccount.push(statement.row.aXml);
                      }
                   }
                 
        finally {
                  statement.reset();
                }        
        for(var i=0;i<emailAccount.length;i++)    
        {
             var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_email WHERE eName = :myVal and dId =:myVal1");
                  statement.params.myVal = emailAccount[i].split("_")[0];
                  statement.params.myVal1 = offdeviceid;
            try{
                 statement.executeStep();
            }
            finally{
                statement.reset();
            }
                
        }        
     /*更新离线设备的通讯录状态信息*/
      var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT dName FROM td_device where dId = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                       var deviceNS=statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }   
      var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
                           SET cStatus = 3  where cDeviceName = :myVal");
      statement.params.myVal = deviceNS;
      try {
        while (statement.executeStep()) {
            continue;
        }
      }
    finally {
        statement.reset();
    }
    /*更新远程邮件目录树，删除离线设备*/            
    breakoffliveoffDevice(offdeviceid);             
     
        /*删除数据库中存储的设备信息*/
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_device WHERE dUDN = :myVal");
            statement.params.myVal = id;
            try{
                 statement.executeStep();
            }
            finally{
                statement.reset();
            }
            
  
}

function toShowlinkDevicePanel(dev,dbdev)
{
    //var folderPane =  document.getElementById('folderPaneBox');
    //var selectMenuItem = document.getElementById("connectManagerPanel");
    //alert(newdevice);
     gEN.deviceid = dev.uuid;
     //alert(gEN.deviceid);
    if(gDeviceWindowObj === null || gDeviceWindowObj.closed){  
        gDeviceWindowObj = window.openDialog(
                "chrome://messenger/content/onedeviceWindow.xul", 
                "deviceWindowName",
                "chrome, dialog, centerscreen",dev,dbdev);
    }else{
        gDeviceWindowObj.close();
    }
}
/*断开服务时删除数据库中的设备信息表*/
function deleteDeviceInfoInDB()
{
    /*删除原设备表并建立新设备表*/
   dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_device");
   dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_device (\
                dId INTEGER PRIMARY KEY AUTOINCREMENT, dName CHAR(50) NOT NULL,  dLocation TEXT NOT NULL, dUDN TEXT NOT NULL,\
                dStatus INTEGER DEFAULT 0, dHandleStatus INTEGER DEFAULT 0, dListId INTEGER)");
   /*删除原账户信息表并建立新账户信息表*/
    dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_account");
    dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_account (\
                                                aId INTEGER PRIMARY KEY AUTOINCREMENT,\
                                                aName CHAR(50) NOT NULL,aPwd CHAR(50) \
                                                NOT NULL,aXml TEXT NOT NULL,aServiceType\
                                                INTEGER,dId INTEGER NOT NULL,aLastStatus \
                                                INTEGER DEFAULT 0,aLocalStatus INTEGER DEFAULT 0,\
                                             aRemoteStatus INTEGER DEFAULT 0,aControlType INTEGER DEFAULT 0)");
   /*删除原邮件头信息表并建立新邮件头信息表*/
   dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_email");   
   dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_email (\
                                              eId           INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
                                              eMessageId   INTEGER NOT NULL,\
                                              eSubject      VARCHAR NOT NULL,\
                                              eFrom      VARCHAR NOT NULL,\
                                              eTo      VARCHAR NOT NULL,\
                                              eReply      VARCHAR NOT NULL,\
                                              eFolder     VARCHAR NOT NULL,\
                                              eName     VARCHAR NOT NULL,\
                                              eDate      DATETIME NOT NULL,\
                                              dId   INTEGER NOT NULL)"); 
  /*删除原邮件头信息表并建立新邮件头信息表*/
//   dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_contact");   
//   dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_email (\
//                                             cId           INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
//                                             cDeviceName        VARCHAR NOT NULL,\
//                                             cContactName         VARCHAR NOT NULL,\
//                                             cEmailAddress      VARCHAR NOT NULL,\
//                                             cAccount               VARCHAR NOT NULL,\
//                                             cUri                       VARCHAR,\
//                                             cStatus                  INTEGER DEFAULT 1)"; 
   //alert(5);
   var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
                           SET cStatus = 3");
      try {
        while (statement.executeStep()) {
            continue;
        }
      }
    finally {
        statement.reset();
    }
   dDeviceSqlite.onClose();
   //alert(6);
}

/*控制UPNP服务*/
function controlUpnpService()
{
    
    var selectMenuItem = document.getElementById("swithUpnpServ");
    if(selectMenuItem.getAttribute("checked"))
    {
        upnpInit();
        //alert(1);        
    }else{
        //alert(2);
        closeUpnpService();
    }
}